<script setup>
import ChatBox from "@/components/chat-box.vue";
import {nextTick, ref, watch} from "vue";
import {systemInfo, userInfo} from '@/stores/userStore.js'
import MarkdownIt from 'markdown-it';
import {appendMessage, searchChatHistoryDetail} from '@/api/http/chat.js'

const markdown = new MarkdownIt();


const formVal = ref({});
const messageData = ref({
  "messages": []
});
const refreshCard = ref(true);
const sendButtonLoading = ref(false);
const chatHistoryBody = ref();


const searchHistoryDetail = async () => {
  searchChatHistoryDetail({
    "chatId": systemInfo().requestId
  }).then(res => {
    refreshCard.value = false;
    messageData.value = res.data.data;
    refreshCard.value = true;
  })
}

const handleMessage = async (param) => {
  sendButtonLoading.value = true;

  messageData.value.messages.push({
    "role": "user",
    msgObj: {
      "message": param.message
    }
  })
  if (messageData.value.title === undefined) {
    messageData.value.title = param.message;
  }


  formVal.value = {};
  const start = Date.now();
  let response = await appendMessage({
    "chatId": systemInfo().requestId
    , ...param
  });

  messageData.value.messages.push({
    "role": "assistant",
    msgObj: {
      "message": "",
      "mdMessage": ""
    }
  })

  let last = messageData.value.messages.length - 1;


  const reader = response.body.getReader();
  const textDecode = new TextDecoder();
  while (true) {
    const {done, value} = await reader.read();
    if (done) break; // 如果流结束，退出循环
    // 解码并处理数据
    const chunk = textDecode.decode(value);
    let mdMessage = messageData.value.messages[last].msgObj.mdMessage;
    messageData.value.messages[last].msgObj = {
      ...messageData.value.messages[last].msgObj,
      "mdMessage": mdMessage + chunk
    }
  }
  const useTime = Date.now() - start;
  messageData.value.messages[last].msgObj = {
    ...messageData.value.messages[last].msgObj,
    "message": `用时${useTime / 1000}秒`
  }
  sendButtonLoading.value = false;

}

const mdToHtmlFunc = (text) => {
  return markdown.render(text);
}

const initFunc = () => {
  messageData.value = {"messages": []}
}

watch(() => messageData
    , async (oldVal, newVal) => {
      nextTick(() => {
        chatHistoryBody.value.scrollTop = chatHistoryBody.value.scrollHeight;
      })
    },
    {deep: true}
)
defineExpose({
  searchHistoryDetail, handleMessage, initFunc,
  formVal
})


</script>

<template>
  <div class="chat-history-wrapper">
    <div class="chat-history-header">
      <h2>{{ messageData.title }}</h2>
    </div>
    <div class="chat-history-body" ref="chatHistoryBody">
      <template v-for="msg in messageData.messages">
        <div style="align-self: flex-end;display: flex;align-items: center" v-if="msg.role ==='user'">
          <el-card>{{ msg.msgObj.message }}</el-card>
          <el-avatar :src="userInfo().avatarUrl" style="height: 40px"/>
        </div>
        <div style="display: flex" v-else-if="msg.role==='assistant'">
          <div>
            <el-avatar src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png"/>
          </div>
          <div style="width: 90%">
            <el-card style="width: fit-content" v-if="msg.msgObj.message !== undefined">{{
                msg.msgObj.message
              }}
            </el-card>
            <div style="margin-left: 50px" v-html="mdToHtmlFunc(msg?.msgObj?.mdMessage??'')"></div>
          </div>
        </div>
      </template>

    </div>
    <div class="chat-history-foot">
      <chat-box
          v-model:from-val="formVal"
          v-model:sendButtonIsLoading="sendButtonLoading"
          @handleMessage="handleMessage"
      />
    </div>
  </div>
</template>

<style scoped lang="scss">
.chat-history-wrapper {
  width: 100%;
  height: 100%;

  .chat-history-header {
    height: 80px;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .chat-history-body {
    height: calc(100% - 270px);
    padding: 0 10px 10px 10px;
    display: flex;
    flex-direction: column;
    align-content: flex-start;
    align-items: flex-start;
    overflow: scroll;

    & > div {
      margin: 5px 0 10px 0;
    }
  }

  .chat-history-foot {
    width: 100%;
    display: flex;
    justify-content: center;
  }
}
</style>